package cn.shuto.liferay.plugin.chart.service.permission;

import cn.shuto.liferay.plugin.chart.service.model.Option;
import cn.shuto.liferay.plugin.chart.service.service.OptionLocalServiceUtil;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.staging.permission.StagingPermissionUtil;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.security.permission.PermissionChecker;

public class OptionModelPermission {

	public static void check(
			PermissionChecker permissionChecker, Option option,
			String actionId)
		throws PortalException {

		if (!contains(permissionChecker, option, actionId)) {
			throw new PrincipalException();
		}
	}

	public static void check(
			PermissionChecker permissionChecker, long optionId,
			String actionId)
		throws PortalException, SystemException {

		if (!contains(permissionChecker, optionId, actionId)) {
			throw new PrincipalException();
		}
	}


	public static boolean contains(
		PermissionChecker permissionChecker, Option option,
		String actionId) {

		Boolean hasPermission = StagingPermissionUtil.hasPermission(
			permissionChecker,option.getGroupId(),
			Option.class.getName(),option.getOptionId(),
			"chart-admin", actionId);

		if (hasPermission != null) {
			return hasPermission.booleanValue();
		}

		if (permissionChecker.hasOwnerPermission(
				option.getCompanyId(), Option.class.getName(),
				option.getOptionId(), option.getUserId(), actionId)) {

			return true;
		}

		return permissionChecker.hasPermission(
				option.getGroupId(), Option.class.getName(),
				option.getOptionId(), actionId);
	}

	public static boolean contains(
			PermissionChecker permissionChecker, long optionId,
			String actionId)
		throws PortalException, SystemException {

		Option option = OptionLocalServiceUtil.getOption(optionId);

		return contains(permissionChecker, option, actionId);
	}
}
